package com.qf.sportsevent.adapter;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v4.util.Pools;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by Administrator on 2016/12/16.
 */

public class CommonPagerAdapter<D> extends PagerAdapter{
    private List<D> list;
    private int layoutId;
    private int variableId;
    private Pools.Pool<View> pool=new Pools.SimplePool<>(4);

    public CommonPagerAdapter(List<D> list, int layoutId, int variableId) {
        this.list = list;
        this.layoutId = layoutId;
        this.variableId = variableId;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View rootView=pool.acquire();
        if(rootView==null) {
            rootView = DataBindingUtil.inflate(LayoutInflater.from(container.getContext()), layoutId, container, false).getRoot();
            ViewDataBinding bind = DataBindingUtil.bind(rootView);
            bind.setVariable(variableId,list.get(position));
        }
        container.addView(rootView);
        return rootView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
        pool.release(view);
    }
}
